package erp_services

import (
	"database/sql"
	"time"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/global"
)

type lineService struct {
}

var LineService = new(lineService)

// 根据ID查询数据
func (lineService *lineService) SetById(station_id, line_id string) (line *erp_models.Line, err error) {
	res := global.App.DB.Where("state = ? AND  station_id = ? AND line_no = ? ", 1, station_id, line_id).First(&line)

	if res.RowsAffected > 0 {
		line.LastTime = sql.NullTime{Valid: true, Time: time.Now()}
		line.Online = 1
		global.App.DB.Save(&line)
	} else {
		return nil, res.Error
	}

	return
}

func (lineService *lineService) SetAllById(station_id string) (lines []*erp_models.Line, err error) {
	// 查找所有匹配的记录
	res := global.App.DB.Where("state = ? AND station_id = ?", 1, station_id).Find(&lines)

	if res.Error != nil {
		return nil, res.Error
	}

	if len(lines) > 0 {
		// 更新所有找到的记录
		for _, line := range lines {
			line.LastTime = sql.NullTime{Valid: true, Time: time.Now()}
			line.Online = 1
			if err := global.App.DB.Save(line).Error; err != nil {
				return nil, err
			}
		}
		return lines, nil
	}

	return nil, nil
}
